import csv
import os

from PIL import Image

csv_folder = "/Users/user/Desktop/tt/csv/"
png_folder = "/Users/user/Desktop/tt/png/"
out_folder = "/Users/user/Desktop/tt/train"
os.makedirs(out_folder, exist_ok=True)
patch_size = 64

for png in os.listdir(png_folder):
    png_name = png.replace(".png", "")
    png_file = Image.open(png_folder + png)
    pname, px, py = png_name.split("_")
    csv_file = csv_folder + png_name + ".csv"
    if not os.path.exists(csv_file):
        continue
    csv_reader = csv.reader(open(csv_file))
    for row in csv_reader:
        # print(row)
        x = int(row[0])
        y = int(row[1])
        x_start = x - patch_size // 2
        y_start = y - patch_size // 2
        x_end = x + patch_size // 2
        y_end = y + patch_size // 2
        crop_patch = png_file.crop((x_start, y_start, x_end, y_end))
        crop_patch.save(f"{out_folder}/{pname}_{int(px) + x}_{int(py) + y}.png")

